package org.xs.web.http.validate;

import java.util.regex.Pattern;

import org.xs.web.util.Helpers;

public class Validators {
	private static final Pattern number = Pattern.compile("\\d+");
	private static final Pattern decimal = Pattern.compile("\\d+|\\d+\\.\\d+");
	
	public boolean notnull(Object value){
		if(value != null && value.getClass().isArray()){
			return ((Object[]) value).length > 0;
		}else{
			return value != null;
		}
	}
	 
	public boolean regex(String regex,Object value){
		Pattern pt = Pattern.compile(regex);
		return regexCommon(value,pt);
		 
	}
	private boolean regexCommon(Object value,Pattern pt) {
		if(value == null) return true;
		if(value.getClass().isArray()){
			for(Object v : (Object[])value){
				if(!pt.matcher((String)v).matches()){
					return false;
				}
			}
			return true;
		}else{
			return pt.matcher((String)value).matches();
		}
	}
	
	public boolean number(Object value){
		return regexCommon(value,number);
	}
	
	
	public boolean decimal(Object value){
		return regexCommon(value,decimal);
	}
	
	public boolean minlength(String lens,Object value){
		if(value == null) return true;
		int len = Helpers.toInt(lens, 1);
		if(value.getClass().isArray()){
			for(Object v : (Object[])value){
				if(((String)v).length() < len+1 ){
					return false;
				}
			}
			return true;
		}else{
			return((String)value).length() > len+1;
		}
	}
	
	public boolean range(String r,String l,Object value){
		if(value == null) return true;
		int st = Helpers.toInt(r, 1);
		int et = Helpers.toInt(l, 1);
		if(value.getClass().isArray()){
			for(Object v : (Object[])value){
				if(((String)v).length() < et +1 && ((String)v).length() > st-1){
					return false;
				}
			}
			return true;
		}else{
			return ((String)value).length() > st-1 && ((String)value).length() < et+1;
		}
		
	}
	
}
